#!/bin/env python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    Add By :e4ting e4ting@gmail.com 2023-09-24 16:33:29
"""
import sys,os
import json,time
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack
from textwrap import dedent

from flask_restful import Resource
from flask         import redirect,request,make_response

from e4ting          import util,log
from core.webhook import Robot,MessageTemp,HookSender

class WebHooks(Resource):
    ''' 机器人管理 '''
    #----------------------------------------------------------------------
    def __init__(self):
        super(WebHooks, self).__init__()

    def _list_(self, page=1, size=20, total=100, **data):
        hooks = HookSender.load_all(**data)
        return hooks

    def get(self, id=0, **kwargs):
        params = dict(request.args)
        hooks = self._list_(**params)
        data = [ _.webdumps() for _ in hooks]
        data.sort(key=lambda x:x.get("uptime"), reverse=True)
        return dict(code=200, data=data, total=len(data))

    def put(self, id=0, **kwargs):
        data = request.json
        log.info(data)
        HookSender.update(name=data.get("name"),
                    event=data.get("event"),
                    robot=data.get("robot"),
                    template=data.get("template"),
                    )
        return dict(code=200, data="成功了")

    def post(self, id=0, **kwargs):
        """
            修改 机器人
        """
        data = request.json
        _id = id or data.get("id")
        # log.info(f"修改机器人 {_id} {data}")
        # if not _id:
        #     return dict(code=400, data="修改失败")
        # _id = int(_id)
        HookSender.update(_id,
                    name=data.get("name"),
                    event=data.get("event"),
                    robot=data.get("robot"),
                    template=data.get("template")
                    )
        return dict(code=200, data="修改成功 : {name}".format(**data))

    def delete(self, id=0, **kwargs):
        """
            删除 机器人
        """
        _id = id or request.args.get("id") or request.json.get("id")
        log.info(f"删除模板 {_id}")
        if not _id:
            return dict(code=400, data="删除失败")
        ret = HookSender.delete(_id)
        if not ret:
             return dict(code=500, data="删除失败")
        return dict(code=200, data="删除成功 : {name} ( {_id} )".format(**ret))

